<!--
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-17 19:31:09
-->
<template>
  <el-card>
    <template #header>
      <el-button type="primary" :icon="Plus" @click="centerDialogVisible = true">添加</el-button>
    </template>

    <el-table :data="trademarkDate.trademarkList" style="width: 100%" stripe border>
      <el-table-column type="index" label="序号" width="90" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="logoUrl" label="品牌 LOGO">
        <template #default="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="warning" :icon="Edit" size="small" @click="updateTrademark(row.id)"
            >修改</el-button
          >
          <el-button type="danger" :icon="Delete" size="small" @click="delTrademark(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="trademarkDate.page"
      v-model:page-size="trademarkDate.limit"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="trademarkDate.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      v-model="centerDialogVisible"
      :title="isAddorUpdate ? '添加品牌' : '编辑品牌'"
      width="50%"
      align-center
      @close="dialogClose"
    >
      <el-form ref="formRef" :model="formData" label-width="120px" :rules="rules">
        <el-form-item label="品牌名称:" prop="tmName">
          <el-input v-model="formData.tmName" />
        </el-form-item>
        <el-form-item label="品牌 Logo:" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.logoUrl" :src="formData.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogOk"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
import {
  reqAddBaseTrademarkRes,
  reqBaseTrademark,
  reqBaseTrademarkDetail,
  reqUpdateBaseTrademark,
  type BaseTrademarkItem,
  reqRemoveRes
} from '@/api/trademark'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance, type UploadProps } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

// 添加修改删除
const centerDialogVisible = ref(false)
const formData = ref({
  tmName: '',
  logoUrl: ''
})

const formRef = ref<FormInstance>()

const isAddorUpdate = ref(true)

const rules = reactive({
  tmName: [{ required: true, message: '请输入品牌名', trigger: 'blur' }],
  logoUrl: [{ required: true, message: '请上传图片', trigger: 'change' }]
})

const delTrademark = (row: BaseTrademarkItem) => {
  ElMessageBox.confirm(`确定要删除${row.tmName}吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await reqRemoveRes(row.id)
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
      }
      getTrademarkList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功'
      })
    })
}

const updateTrademark = async (id: number) => {
  isAddorUpdate.value = false
  centerDialogVisible.value = true
  const res = await reqBaseTrademarkDetail(id)
  if (res.code === 200) {
    formData.value = res.data
  }
}

const dialogOk = async () => {
  await formRef.value?.validate()
  const res = isAddorUpdate.value
    ? await reqAddBaseTrademarkRes(formData.value)
    : await reqUpdateBaseTrademark(formData.value)

  if (res.code === 200) {
    ElMessage.success(isAddorUpdate.value ? '添加成功' : '编辑成功')
  }
  getTrademarkList()

  centerDialogVisible.value = false
}

const dialogClose = () => {
  formRef.value?.resetFields()
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  formData.value.logoUrl = URL.createObjectURL(uploadFile.raw!)
  formRef.value?.validateField('logoUrl')
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
// #region 渲染品牌列表逻辑
interface reqTrademarkRecord {
  id: number
  logoUrl: string
  tmName: string
}
interface trademarkState {
  page: number
  limit: number
  total: number
  trademarkList: reqTrademarkRecord[]
}

// 定义列表数据
const trademarkDate: trademarkState = reactive({
  page: 1,
  limit: 10,
  total: 0,
  trademarkList: []
})

const handleSizeChange = (val: number) => {
  trademarkDate.limit = val
  getTrademarkList()
}
const handleCurrentChange = (val: number) => {
  trademarkDate.page = val
  getTrademarkList()
}

const getTrademarkList = async () => {
  const res = await reqBaseTrademark(trademarkDate.page, trademarkDate.limit)
  if (res.code === 200) {
    trademarkDate.total = res.data.total
    trademarkDate.trademarkList = res.data.records
  }
}
onMounted(() => {
  getTrademarkList()
})
//#endregion
</script>

<script lang="ts">
export default {
  name: 'TrademarkView'
}
</script>

<style lang="scss" scoped>
.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
